#!/usr/bin/perl
use strict; use warnings;


if(scalar(@ARGV) != 1){
	print  "Warning: grav_check.pl was called with invalid paramaters\n";
	exit 1;
}
# number of grav instances node *SHOULD* be running
my $goodInstances = $ARGV[0];
# number of screens grav *SHOULD* be running on
# currently not used, but whatever
# my $goodScreens = $ARGV[1];


# put all running grav commands into an array
my @gravs = `ps ax | grep grav- | grep -v grep`;
# count the elements in the array
my $runningGravs = scalar(@gravs);

# exit and print error if Grav is not running at all
# no reason to continue the script
if ($runningGravs == 0){
	print "Critical: Grav is not running\n";
	exit 2;
}

# the -sx value specified in the grav parameter string
my @resolutions;
# loops through each instance of grav running
# and finds which screens have grav running
foreach(@gravs){ 
	$_ =~ /-sx\s(\d*)\s\b/;
	push(@resolutions,$1); 	
}

# have resolutions listed in an increasing manner
@resolutions = sort(@resolutions);

# #of gravs not running
my $NRN = $goodInstances - $runningGravs;
# if a grav instance is not running
if ($runningGravs < $goodInstances) {
        print "Critical: $NRN of $goodInstances grav instances are  not running\n";
        exit 2;
}

# last used element in the array
my $last1 = "last1"; 
# loop through each instance of grav running
# to see if more than one instance is running on the same screen
foreach(@resolutions){
	if($_ eq $last1){
		print "Warning: Two or more instances of Grav are running at X coordinate: $_\n"; 
		exit 1;
	}
	$last1 = $_;
}

# an extra intances of grav is running
if($runningGravs > $goodInstances){
        print "Warning: Grav is running on an extra screen\n";
        exit 1;
}

# Basic catch all. Shouldn't really ever get here.
if($runningGravs != $goodInstances){
	print "Critical: CurentlyRunningGravs != ShouldBeRunningGravs\n";
	exit 2;
}

# everything should have been caught by this point
# grav is running normally
if($runningGravs == $goodInstances){
	print "Okay: Grav Instances are running normally\n";
	exit 0;
}
